package com.jh.paymentchannel.qctpos;

import cn.jh.common.utils.CommonConstants;
import com.jh.paymentchannel.qctpos.eumn.QctposBaseEnum;
import com.jh.paymentchannel.qctpos.pojo.request.QctPosQueryRequest;
import com.jh.paymentchannel.qctpos.pojo.request.QctposBaseRequest;
import com.jh.paymentchannel.qctpos.pojo.request.QctposCallRequest;
import com.jh.paymentchannel.qctpos.pojo.response.QctposBaseResponse;
import com.jh.paymentchannel.qctpos.util.QctposBaseUtils;
import com.jh.paymentchannel.util.SignUtils;
import com.jh.paymentchannel.util.Util;
import net.sf.json.JSONObject;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Controller
@EnableAutoConfiguration
public class QctposTestService {

    @Autowired
    Util util;

    @Value("${qctpos.key}")
    private String key;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/qctpos/call")
    public @ResponseBody
    Object call(QctposCallRequest qctposCallRequest) {
        logger.info("进入全城涛回调接口================" + qctposCallRequest.toString());
        String string = QctposBaseUtils.signString(QctposBaseUtils.objToTreeMap(qctposCallRequest, QctposBaseUtils.getVerifyList()), key);
        logger.error("全城涛签名验证sign=====" + string + "===========返回sign" + qctposCallRequest.getSign());
        QctposBaseResponse qctposBaseResponse = new QctposBaseResponse();
        if (!string.equals(qctposCallRequest.getSign())) {
            qctposBaseResponse.setReturn_code(QctposBaseEnum.SIGN_ERROR.getValue());
            qctposBaseResponse.setReturn_msg(QctposBaseEnum.SIGN_ERROR.getDesc());
            return qctposBaseResponse;
        }
        /**调用下单，需要得到用户的订单信息*/
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/update";
        /**根据的用户手机号码查询用户的基本信息*/
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("status", "1");
        requestEntity.add("order_code", qctposCallRequest.getOut_trade_no());
        logger.info("接口/v1.0/transactionclear/payment/update--参数================" + qctposCallRequest.getOut_trade_no());
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        logger.info("接口/v1.0/transactionclear/payment/update--RESULT================" + result);
        qctposBaseResponse.setReturn_code(QctposBaseEnum.SUCCESS.getValue());
        qctposBaseResponse.setReturn_msg(QctposBaseEnum.SUCCESS.getDesc());
        return qctposBaseResponse;
    }


    /**
     * 订单查询
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "v1.0/qct/pay/order/query")
    public @ResponseBody Object orderQuery(
            @RequestParam("out_trade_no") String outTradeNo,//商户支付订单号
            @RequestParam("tradeNo") String tradeNo, //交易流水号
            @RequestParam("shopId") String shopId,//交易流水号
            @RequestParam("deviceId") String deviceId //终端号
    ) {
        HashMap<Object, Object> map = new HashMap<>();
        try {
            /**订单查询*/
            String url = "http://test.api.qctpos.com/partnerpay/SearchTrade";
            MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<String, Object>();
            requestEntity=fzParams(shopId, deviceId, outTradeNo, tradeNo);

            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.postForObject(url, requestEntity, String.class);

            JSONObject jsonObject = JSONObject.fromObject(result);
            logger.info(jsonObject.toString());
            if (jsonObject.isNullObject() || result == null) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "失败");
                logger.info("参数获取失败");
                return map;
            }
            String resCode = jsonObject.getString("return_code");
            String resMsg = jsonObject.getString("return_msg");
            if (resCode.equals("00000")) {
                logger.info("返回结果====================" + resCode + resMsg);
                QctPosQueryRequest posQueryRequest = new QctPosQueryRequest();
                posQueryRequest.setOut_trade_no(jsonObject.getString("out_trade_no"));
                Double amount = (Double) jsonObject.get("receipt_amount");
                posQueryRequest.setReceipt_amount(amount);
                posQueryRequest.setPay_status(jsonObject.getString("pay_status"));
                posQueryRequest.setPay_channel(jsonObject.getString("pay_channel"));
                posQueryRequest.setTrade_date(jsonObject.getString("trade_date"));
                posQueryRequest.setTag_code1(jsonObject.getString("tag_code1"));
                posQueryRequest.setTag_code1(jsonObject.getString("tag_code2"));
                logger.info("结果============================" + posQueryRequest.toString());
                map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                map.put(CommonConstants.RESP_MESSAGE, "订单查询成功");
                map.put(CommonConstants.RESULT, posQueryRequest);

            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "订单查询失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

      public  MultiValueMap  fzParams(String shopId, String deviceId, String outTradeNo, String tradeNo) throws Exception {
          //加密
        MultiValueMap<String, Object> requestEntity = new LinkedMultiValueMap<String, Object>();
        QctposBaseRequest qctposBaseRequest = new QctposBaseRequest();
        qctposBaseRequest.setMethod("qct.trade.search");
        qctposBaseRequest.setCharset("utf-8");
        qctposBaseRequest.setMch_id(shopId);
        qctposBaseRequest.setDevice_id(deviceId);
        qctposBaseRequest.setSign_type("MD5");
        qctposBaseRequest.setVersion("1.0");

        List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
        nvps.add(new BasicNameValuePair("method", qctposBaseRequest.getMethod()));
        nvps.add(new BasicNameValuePair("charset", qctposBaseRequest.getCharset()));
        nvps.add(new BasicNameValuePair("mch_id", qctposBaseRequest.getMch_id()));
        nvps.add(new BasicNameValuePair("device_id", qctposBaseRequest.getDevice_id()));
        nvps.add(new BasicNameValuePair("sign_type", qctposBaseRequest.getSign_type()));
        nvps.add(new BasicNameValuePair("version", qctposBaseRequest.getVersion()));
        nvps.add(new BasicNameValuePair("out_trade_no", outTradeNo));
        nvps.add(new BasicNameValuePair("tradeNo", tradeNo));
        qctposBaseRequest.setSign(SignUtils.signMD5Data(nvps, key));
          requestEntity.add("method", "qct.trade.search");
          requestEntity.add("charset",  "utf-8");
          requestEntity.add("mch_id", shopId);
          requestEntity.add("device_id", "".equals(deviceId)?null :deviceId);
          requestEntity.add("sign_type", "MD5");
          requestEntity.add("version", "1.0");
          requestEntity.add("sign",SignUtils.signMD5Data(nvps,key));
        requestEntity.add("out_trade_no",  "".equals(outTradeNo)?null :outTradeNo);
        requestEntity.add("tradeNo", tradeNo);
     return requestEntity;
    }


}
